﻿using AutoMapper;
using ImoviesBlazor.Server.Repository;
using ImoviesBlazor.Shared.Dtos;
using ImoviesBlazor.Shared.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ImoviesBlazor.Server.Controllers
{

    /// <summary>
    /// 电影播放链接控制器
    /// </summary>
    [Authorize]
    [ApiController]
    [Route("api/[controller]")]
    public class MovieVlinkController : ControllerBase
    {
        private readonly IMovieVlinkRepository _movieVlinkRepository;
        private readonly IMapper _mapper;

        public MovieVlinkController(IMovieVlinkRepository movieRepository, IMapper mapper)
        {
            this._movieVlinkRepository = movieRepository;
            this._mapper = mapper;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="movieVlink"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Add([FromBody] MovieVlinkForCreateDto movieVlink)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            var t = _mapper.Map<MovieVlink>(movieVlink);
            _movieVlinkRepository.AddMovieVlink(t);
            bool res = await _movieVlinkRepository.SaveAsync();
            if (!res)   //保存失败
            {
                Response.StatusCode = 500;
                return Content("操作失败");
            }
            return Ok();
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="movieVlink"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ActionResult> Update([FromBody] MovieVlinkForUpdateDto movieVlink)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            var t = _mapper.Map<MovieVlink>(movieVlink);
            _movieVlinkRepository.UpdateMovieVlink(t);
            bool res = await _movieVlinkRepository.SaveAsync();
            if (!res)   //保存失败
            {
                Response.StatusCode = 500;
                return Content("操作失败");
            }
            return Ok();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult> Delete([FromRoute] uint id)
        {
            await _movieVlinkRepository.DeleteMovieVlink(id);
            bool res = await _movieVlinkRepository.SaveAsync();
            if (!res)   //保存失败
            {
                Response.StatusCode = 500;
                return Content("操作失败");
            }
            return Ok();
        }
    }
}
